package com.yc.backstage.common.service;

import com.yc.backstage.entity.LoginUser;
import com.yc.backstage.entity.SysUser;
import com.yc.backstage.service.SysPermissionService;
import com.yc.backstage.service.SysRoleService;
import com.yc.backstage.service.SysUserService;
import com.yc.common.enums.UserStatus;
import com.yc.common.expection.BusinessException;
import com.yc.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Classname UserDetailServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/7/26 15:34
 * @Created by Mikechen
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Autowired
    private SysUserService SysUserService;
    //权限service
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 校验user是否存在，从缓存 db 或者其他地方获取
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        SysUser user = SysUserService.selectUserByUserName(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new BusinessException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BusinessException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BusinessException("对不起，您的账号：" + username + " 已停用");
        }
        return createLoginUser(user);
    }
    //创建一个LoginUser 放入信息
    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user, permissionService.getMenuPermission(user),sysRoleService.selectRoleByUserId(user.getUserId()));
    }
}
